package com.it.utils;

import javax.imageio.ImageIO;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import javax.imageio.stream.FileImageOutputStream;
import javax.imageio.stream.ImageOutputStream;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
/**
 * @desc:
 * @author: panxiyi
 * @date: 2023/6/29 10:26 上午
 */
public class ImageUtils {

    public static void main(String[] args) {
        try {
            // 加载图像文件
            File inputImage = new File("/Users/mtpxy/Desktop/space/WechatIMG242.jpeg");
            BufferedImage image = ImageIO.read(inputImage);
            // 获取 JPEG 图像编写器
            ImageWriter jpegWriter = ImageIO.getImageWritersByFormatName("JPEG").next();
            ImageWriteParam jpegWriteParam = jpegWriter.getDefaultWriteParam();
            // 设置压缩质量：0.0（最低）至 1.0（最高）
            float compressionQuality = 0.2f; // 缩小到50%的质量
            jpegWriteParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
            jpegWriteParam.setCompressionQuality(compressionQuality);
            // 将压缩后的图像写入输出文件
            File outputImage = new File("/Users/mtpxy/Desktop/space/certificate.jpg");
            try (ImageOutputStream outputStream = new FileImageOutputStream(outputImage)) {
                jpegWriter.setOutput(outputStream);
                jpegWriter.write(null, new javax.imageio.IIOImage(image, null, null), jpegWriteParam);
            }
            System.out.println("Image compressed successfully");
        } catch (IOException e) {
            System.err.println("Error while compressing image: " + e.getMessage());
        }
    }
}
